package cn.com.shinho.hg.core.feign;

import cn.com.shinho.hg.core.common.exception.CoreExceptionEnum;
import cn.com.shinho.hg.core.common.exception.ServiceException;
import cn.com.shinho.hg.core.util.JsonUtil;
import com.xiaoleilu.hutool.io.IoUtil;
import feign.Response;
import feign.codec.ErrorDecoder;

import java.io.IOException;
import java.util.Map;

/**
 * hg自己的feign错误解码器（为了feign接收到错误的返回，转化成hg可识别的ServiceException）
 *
 * @author Mr.Ye
 * @Date 2018/4/20 23:14
 */
public class HGFeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        String resposeBody;
        try {
            if (response == null || response.body() == null) {
                if (response != null && response.status() == 404) {
                    return new ServiceException(CoreExceptionEnum.REMOTE_SERVICE_NULL);
                } else {
                    return new ServiceException(CoreExceptionEnum.SERVICE_ERROR);
                }
            }
            resposeBody = IoUtil.read(response.body().asInputStream(), "UTF-8");

        } catch (IOException e) {
            return new ServiceException(CoreExceptionEnum.IO_ERROR);
        }
        Map jsonMap = JsonUtil.toObject(resposeBody, Map.class);
        Integer code = (Integer) jsonMap.get("code");
        String message = jsonMap.get("message").toString();
        if (message == null) {
            message = CoreExceptionEnum.SERVICE_ERROR.getMessage();
        }
        if (code == null) {
            //status为spring默认返回的数据
            Integer status = (Integer)jsonMap.get("status");
            if (status == null) {
                return new ServiceException(CoreExceptionEnum.SERVICE_ERROR.getCode(), message);
            } else {
                return new ServiceException(status, message);
            }
        } else {
            return new ServiceException(code, message);
        }
    }
}